#include "SelectableComponent.h"
#include "BoundingBox.h"
#include "PhysicsTask.h"

const HashedString SelectableComponent::type("SelectableComponent");

const HashedString& SelectableComponent::Type()
{
	return type;
}

SelectableComponent::SelectableComponent( Entity* parent ) : IComponent(parent)
{
	m_position = new DoubleValueTrigger<Maths::Vector3D>(0, 0);
}

SelectableComponent::SelectableComponent( Pointer<RigidBody>& body, Entity* parent ) : m_body(body), IComponent(parent)
{
	m_position = new DoubleValueTrigger<Maths::Vector3D>(0, 0);
}

SelectableComponent::~SelectableComponent()
{
}

Pointer<RigidBody>& SelectableComponent::getBody()
{
	return m_body;
}

Pointer<TriggerBase>& SelectableComponent::getPosition()
{
	return m_position;
}

void SelectableComponent::setPosition( Maths::Vector3D& position )
{
	DoubleValueTrigger<Maths::Vector3D>& posTrigger = *(DoubleValueTrigger<Maths::Vector3D>*)((TriggerBase*)(m_position.getPointer()));
	posTrigger = position;
	m_body->setPosition(position);
}

Maths::Vector3D SelectableComponent::Position()
{
	return m_body->getPosition().getObject();
}

void SelectableComponent::ReceiveMessage( IMessage* message )
{
}

std::string SelectableComponent::ToString() const
{
	std::string str;
	for (IShape::Vector_t::iterator it = m_body->getShapes().begin(); it != m_body->getShapes().end(); ++ it)
	{
		str += (*it)->Type().getString();
		str += (*it)->ToString();
		btTransform t((*it)->getLocalOffset());

		char buffer[50];
		sprintf_s(buffer, 50, "%.3f %.3f %.3f %.3f", t.getOrigin().x(), t.getOrigin().y(), t.getOrigin().z(), t.getOrigin().w());

		str += buffer;
	}
	return str;
}

bool SelectableComponent::ToXML( tinyxml2::XMLPrinter& printer )
{
	for (IShape::Vector_t::iterator it = m_body->getShapes().begin(); it != m_body->getShapes().end(); ++ it)
	{
		printer.OpenElement("Shape");
		printer.PushAttribute("Type", (*it)->Type().getString().c_str());
		btTransform t((*it)->getLocalOffset());
		std::string str;

		char buffer[50];
		sprintf_s(buffer, 50, "%.3f %.3f %.3f %.3f", t.getOrigin().x(), t.getOrigin().y(), t.getOrigin().z(), t.getOrigin().w());

		str += buffer;

		printer.PushAttribute("Offset", str.c_str());
		printer.PushAttribute("Detail", (*it)->ToString().c_str());
		printer.CloseElement();
	}
	return true;
}